<template>
    <view class="news-detail">
        <view class="news-header">
            <text class="news-title">{{ newsDetail.title }}</text>
            <view class="news-meta">
                <text class="news-category">{{ newsDetail.categoryLabel }}</text>
                <text class="news-time">{{ newsDetail.createTime | formatDate }}</text>
            </view>
        </view>

        <view class="news-content">
            <!-- 视频内容 -->
            <video v-if="newsDetail.videoUrl" :src="newsDetail.videoUrl" class="news-video" controls></video>

            <!-- 图片内容 -->
            <image v-if="newsDetail.cover" :src="newsDetail.cover" mode="widthFix" class="news-cover"></image>

            <!-- 富文本内容 -->
            <rich-text v-if="newsDetail.content" :nodes="newsDetail.content" class="news-text"></rich-text>
        </view>

        <!-- 相关推荐 -->
        <view class="related-news" v-if="relatedNews.length">
            <view class="section-title">相关推荐</view>
            <view class="related-item" v-for="(item, index) in relatedNews" :key="index" @tap="goToDetail(item.id)">
                <text class="related-title">{{ item.title }}</text>
            </view>
        </view>

        <!-- 操作栏：点赞、转发 -->
        <view class="actions-bar">
            <view class="action-item" @tap="toggleLike">
                <image :src="isLiked ? like_s : like" mode="widthFix" class="action-icon"></image>
                <text class="action-text">{{ likeCount }}</text>
            </view>
            <view class="action-item" @tap="shareNews">
                <text class="action-text">浏览</text>
                <text class="action-text">{{ shareCount }}</text>
            </view>
            <button open-type="share" class="share-button">
                <image :src="share" mode="widthFix" class="action-icon"></image>
                <text class="action-text">{{ shareCount }}</text>
            </button>
        </view>
    </view>
</template>

<script>
import { getNewsDetail, getRelatedNews } from '@/api/news'; // Import API
import dayjs from 'dayjs'; // Import dayjs

// Mock detail data function (replace with API)
const getMockDetail = (id) => {
    const categories = {
        industry: '行业动态', policy: '政策法规', technology: '技术趋势', case: '应用案例', activity: '活动公告'
    };
    const randomCategoryValue = Object.keys(categories)[Math.floor(Math.random() * Object.keys(categories).length)];
    return {
        id: id,
        title: `模拟资讯详情标题 ${id}`,
        category: randomCategoryValue,
        categoryLabel: categories[randomCategoryValue],
        createTime: dayjs().subtract(Math.floor(Math.random() * 30), 'day').toISOString(),
        content: `<p>这是资讯 ${id} 的详细内容。</p><p>段落二：这里包含一些 <b>加粗</b> 和 <i>斜体</i> 文本。</p><img src="https://via.placeholder.com/690x300/eeeeee/969696?text=Detail+Image+${id}" style="width:100%;"/> <p>段落三：更多内容...</p>`,
        videoUrl: id % 3 === 0 ? 'https://interactive-examples.mdn.mozilla.net/media/cc0-videos/flower.mp4' : '', // Add video for some items
        cover: id % 3 !== 0 ? `https://via.placeholder.com/690x400/dddddd/969696?text=Cover+${id}` : '', // Add cover for items without video
        likeCount: Math.floor(Math.random() * 500),
        shareCount: Math.floor(Math.random() * 200),
        isLiked: Math.random() > 0.5 // Randomly liked
    };
};

const getMockRelated = (id) => {
    const related = [];
    for (let i = 1; i <= 5; i++) {
        const relatedId = parseInt(id) + i;
        if (relatedId <= 100) { // Assume max 100 mock items
            related.push({ id: relatedId, title: `相关推荐 ${relatedId}` });
        }
    }
    return related;
}

export default {
    data() {
        return {
            like: require('../../static/images/like.png'),
            like_s: require('../../static/images/like_s.png'),
            share: require('../../static/images/share.png'),
            share_s: require('../../static/images/share_s.png'),
            newsId: null,
            newsDetail: {},
            relatedNews: [],
            isLiked: false,
            likeCount: 0,
            shareCount: 0
        }
    },
    filters: { // Add filter for date formatting
        formatDate(value) {
            if (!value) return '';
            return dayjs(value).format('YYYY-MM-DD HH:mm');
        }
    },
    onLoad(options) {
        if (options.id) {
            this.newsId = options.id;
            this.loadNewsDetail(this.newsId);
            this.loadRelatedNews(this.newsId);
            // Record reading data (Placeholder for analytics)
            // this.$analytics.track('read_news', { news_id: options.id });
            console.log(`Analytics: Reading news ${options.id}`);
        }
    },
    // Share configuration
    onShareAppMessage(res) {
        if (res.from === 'button') { // From share button
            console.log(res.target)
        }
        return {
            title: this.newsDetail.title || '行业资讯分享',
            path: `/pages/news/detail?id=${this.newsId}`,
            // imageUrl: this.newsDetail.cover // Optional: Use a cover image for sharing
        }
    },
    onShareTimeline() {
        return {
            title: this.newsDetail.title || '行业资讯分享',
            query: `id=${this.newsId}`,
            // imageUrl: this.newsDetail.cover
        }
    },
    methods: {
        async loadNewsDetail(id) {
            try {
                // const res = await getNewsDetail({ id })
                // this.newsDetail = res.data;
                // Assuming API provides categoryLabel, likeCount, shareCount, isLiked

                // --- Using Mock Data --- 
                await new Promise(resolve => setTimeout(resolve, 300)); // Simulate delay
                const mockData = getMockDetail(id);
                this.newsDetail = mockData;
                this.isLiked = mockData.isLiked;
                this.likeCount = mockData.likeCount;
                this.shareCount = mockData.shareCount;
                // --- End Mock Data --- 

                // Set navigation bar title
                uni.setNavigationBarTitle({ title: this.newsDetail.title || '资讯详情' });

            } catch (error) {
                console.error("Failed to load detail:", error);
                uni.showToast({
                    title: '获取资讯详情失败',
                    icon: 'none'
                })
            }
        },
        async loadRelatedNews(id) {
            try {
                // const res = await getRelatedNews({ id })
                // this.relatedNews = res.data

                // --- Using Mock Data --- 
                await new Promise(resolve => setTimeout(resolve, 400)); // Simulate delay
                this.relatedNews = getMockRelated(id);
                // --- End Mock Data --- 

            } catch (error) {
                console.error('获取相关推荐失败', error)
            }
        },
        goToDetail(id) {
            // Use redirect to avoid too many pages in stack for related items
            uni.redirectTo({
                url: `/pages/news/detail?id=${id}`
            })
        },
        toggleLike() {
            // Simulate like action (replace with API call)
            this.isLiked = !this.isLiked;
            this.likeCount += this.isLiked ? 1 : -1;
            // this.$api.likeNews({ id: this.newsId, like: this.isLiked });
            console.log(`Action: ${this.isLiked ? 'Like' : 'Unlike'} news ${this.newsId}`);
        },
        shareNews() {
            // This can be used for custom share logic if open-type="share" is not sufficient
            console.log(`Action: Initiate share for news ${this.newsId}`);
            // For Wechat Mini Program, usually rely on onShareAppMessage
            uni.showShareMenu({
                withShareTicket: true,
                menus: ["shareAppMessage", "shareTimeline"]
            })
        }
    }
}
</script>

<style lang="scss">
.news-detail {
    padding: 30rpx;
    padding-bottom: 120rpx; // Add padding for actions bar

    .news-header {
        margin-bottom: 30rpx;

        .news-title {
            font-size: 36rpx;
            font-weight: bold;
            color: #333;
            line-height: 1.4;
        }

        .news-meta {
            display: flex;
            justify-content: space-between;
            margin-top: 20rpx;
            font-size: 24rpx;
            color: #999;
        }
    }

    .news-content {
        .news-video {
            width: 100%;
            height: 400rpx;
            margin-bottom: 30rpx;
        }

        .news-cover {
            width: 100%;
            margin-bottom: 30rpx;
        }

        .news-text {
            font-size: 30rpx;
            line-height: 1.6;
            color: #333;

            img {
                // Ensure images within rich text are responsive
                max-width: 100% !important;
                height: auto !important;
                display: block; // Avoid extra space below images
            }
        }
    }

    // Actions Bar Styles
    .actions-bar {
        position: fixed;
        bottom: 0;
        left: 0;
        right: 0;
        height: 100rpx;
        line-height: 100rpx;
        display: flex;
        justify-content: space-around;
        align-items: center;
        padding: 15rpx 0;
        background-color: #fff;
        border-top: 1rpx solid #eee;
        box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);
        z-index: 10;

        .action-item,
        .share-button {
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            background: none;
            border: none;
            padding: 0;
            margin: 0;
            line-height: 1.2;
            outline: none;

            &:after {
                // Remove button border
                border: none;
            }

            .action-text {
                font-size: 24rpx;
                color: #666;
                margin-top: 5rpx;
            }
            .action-icon {
                width: 35rpx;
            }
        }

        // Hide default action item when using open-type button
        .action-item.share-trigger {
            display: none;
        }
    }

    .related-news {
        margin-top: 50rpx;
        padding-top: 30rpx;
        border-top: 1rpx solid #eee;

        .section-title {
            font-size: 32rpx;
            font-weight: bold;
            color: #333;
            margin-bottom: 20rpx;
        }

        .related-item {
            padding: 20rpx 0;
            border-bottom: 1rpx solid #eee;

            .related-title {
                font-size: 28rpx;
                color: #666;
                line-height: 1.4;
            }
        }
    }
}
</style>